package com.yycx.module.weixin.provider.controller;

import com.yycx.common.mybatis.model.ResultBody;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author jzy
 * @date 2021/7/31
 */
@AllArgsConstructor
@RestController
@RequestMapping("/common/wx/mp/user/{appid}")
public class WxMpUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final WxMpService wxService;

    @RequestMapping("/userinfo")
    public ResultBody greetUser(@PathVariable String appid, @RequestParam String code) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        try {
            WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken, null);
            return ResultBody.ok(user);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return ResultBody.failed("未知错误");
    }
}
